package com.rtst.widget.tab;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.hindua.ailaaicuaai.MainActivity;
import com.hindua.tab.MyTab;

public class TabFragment extends Fragment {
	private String mPreviousScrTag;
	private String mRootTabTag;
	
	protected TabFragment() {
		mPreviousScrTag = null;
	}
	
	protected TabFragment(String previousScrTag) {
		mPreviousScrTag = previousScrTag;
	}
	
	protected String getPreviousScrTag() {
		return mPreviousScrTag;
	}
	
	protected boolean isPreviousScrTag(String tag) {
		if(mPreviousScrTag == null) return false;
		else return mPreviousScrTag.contains(tag);
	}
	
	public void setRootTabTag(String tag) {
		mRootTabTag = tag;
	}
	
	protected void startFragmentScr(TabFragment fragment, String tag) {
		fragment.setRootTabTag(mRootTabTag);
		FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
		ft.detach(this);
		int containerViewId = ((ITabHost) getActivity()).getContainerViewId();
		ft.add(containerViewId, fragment, containerViewId + tag);
		ft.commit();
	}
	
	public void refresh() {
	}
	
	public void onBack() {
		if(mPreviousScrTag != null) {
			Fragment previousFragment = getActivity().getSupportFragmentManager().findFragmentByTag(mPreviousScrTag);
			if(previousFragment != null) {
				FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
				ft.remove(this);
				ft.attach(previousFragment);
				ft.commit();
			}
		} else {
			if (getActivity().getClass().getSimpleName().equals(MainActivity.class.getSimpleName())) {
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setMessage("Bạn muốn đóng ứng dụng?")
				.setCancelable(true)
				.setPositiveButton("Có", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onDestroy();
						System.runFinalizersOnExit(true);
						System.exit(0);
					}
				})
				.setNegativeButton("Không", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			} else {
				getActivity().finish();
			}
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		setCurTabFragment();
	}
	
	protected void setCurTabFragment() {
		((ITabHost) getActivity()).setCurTabFragment(this);
		Fragment fg = getActivity().getSupportFragmentManager().findFragmentByTag(mRootTabTag);
		if(fg != null && fg instanceof MyTab) {
			((MyTab) fg).setCurTabFragment(this);
		}
	}
}
